/**
 * 小程序预约详情API SDK
 * 提供预约列表、详情查询、取消预约等功能
 */

class MiniappReservationAPI {
    constructor(baseUrl = 'https://yourdomain.com/backend/api/miniapp') {
        this.baseUrl = baseUrl;
        this.token = wx.getStorageSync('userToken') || wx.getStorageSync('openid') || '';
    }

    /**
     * 设置用户token
     * @param {string} token - 用户token或openid
     */
    setToken(token) {
        this.token = token;
        wx.setStorageSync('userToken', token);
    }

    /**
     * 发起API请求
     * @param {string} url - 请求URL
     * @param {Object} options - 请求选项
     * @returns {Promise}
     */
    request(url, options = {}) {
        return new Promise((resolve, reject) => {
            const requestOptions = {
                url: `${this.baseUrl}${url}`,
                method: options.method || 'GET',
                header: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${this.token}`,
                    ...options.header
                },
                data: options.data || {},
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res.data);
                    } else {
                        reject(new Error(`HTTP ${res.statusCode}: ${res.data?.message || '请求失败'}`));
                    }
                },
                fail: (err) => {
                    reject(new Error(`网络错误: ${err.errMsg}`));
                }
            };

            wx.request(requestOptions);
        });
    }

    /**
     * 获取用户预约列表
     * @param {Object} params - 查询参数
     * @returns {Promise}
     */
    async getReservationList(params = {}) {
        try {
            const queryParams = new URLSearchParams({
                action: 'list',
                ...params
            }).toString();
            
            const result = await this.request(`/reservation_details.php?${queryParams}`);
            return result;
        } catch (error) {
            console.error('获取预约列表失败:', error);
            throw error;
        }
    }

    /**
     * 获取预约详情
     * @param {number} id - 预约ID
     * @returns {Promise}
     */
    async getReservationDetail(id) {
        try {
            const result = await this.request(`/reservation_details.php?action=detail&id=${id}`);
            return result;
        } catch (error) {
            console.error('获取预约详情失败:', error);
            throw error;
        }
    }

    /**
     * 根据预约码查询预约信息
     * @param {string} code - 预约码
     * @returns {Promise}
     */
    async getReservationByCode(code) {
        try {
            const result = await this.request(`/reservation_details.php?action=by_code&code=${code}`);
            return result;
        } catch (error) {
            console.error('查询预约码失败:', error);
            throw error;
        }
    }

    /**
     * 取消预约
     * @param {number} id - 预约ID
     * @param {string} reason - 取消原因
     * @returns {Promise}
     */
    async cancelReservation(id, reason = '') {
        try {
            const result = await this.request('/reservation_details.php?action=cancel', {
                method: 'POST',
                data: { id, reason }
            });
            return result;
        } catch (error) {
            console.error('取消预约失败:', error);
            throw error;
        }
    }

    /**
     * 获取用户预约统计
     * @returns {Promise}
     */
    async getReservationStats() {
        try {
            const result = await this.request('/reservation_details.php?action=stats');
            return result;
        } catch (error) {
            console.error('获取预约统计失败:', error);
            throw error;
        }
    }
}

// 创建全局实例
const reservationAPI = new MiniappReservationAPI();

// 导出供页面使用
module.exports = {
    ReservationAPI: MiniappReservationAPI,
    reservationAPI: reservationAPI
};

/**
 * 小程序页面使用示例
 */

// 在页面中引入
// const { reservationAPI } = require('../../utils/reservation-api.js');

// 示例页面代码
const ReservationListPage = {
    data: {
        reservations: [],
        loading: true,
        hasMore: true,
        page: 1,
        searchType: '',
        searchStatus: ''
    },

    onLoad() {
        this.loadReservations();
        this.loadStats();
    },

    // 加载预约列表
    async loadReservations(reset = true) {
        if (reset) {
            this.setData({ 
                page: 1, 
                reservations: [], 
                loading: true 
            });
        }

        try {
            const result = await reservationAPI.getReservationList({
                page: this.data.page,
                limit: 10,
                type: this.data.searchType,
                status: this.data.searchStatus
            });

            if (result.success) {
                const newReservations = reset ? 
                    result.data.list : 
                    [...this.data.reservations, ...result.data.list];
                
                this.setData({
                    reservations: newReservations,
                    hasMore: result.data.pagination.page < result.data.pagination.pages,
                    loading: false
                });
            }
        } catch (error) {
            wx.showToast({
                title: error.message || '加载失败',
                icon: 'none'
            });
            this.setData({ loading: false });
        }
    },

    // 加载更多
    async loadMore() {
        if (!this.data.hasMore || this.data.loading) return;
        
        this.setData({ 
            page: this.data.page + 1 
        });
        await this.loadReservations(false);
    },

    // 筛选预约
    async filterReservations(type = '', status = '') {
        this.setData({
            searchType: type,
            searchStatus: status
        });
        await this.loadReservations();
    },

    // 查看预约详情
    async viewDetail(e) {
        const id = e.currentTarget.dataset.id;
        
        try {
            const result = await reservationAPI.getReservationDetail(id);
            
            if (result.success) {
                // 跳转到详情页面并传递数据
                wx.navigateTo({
                    url: `/pages/reservation-detail/reservation-detail?id=${id}`
                });
            }
        } catch (error) {
            wx.showToast({
                title: error.message || '获取详情失败',
                icon: 'none'
            });
        }
    },

    // 取消预约
    async cancelReservation(e) {
        const id = e.currentTarget.dataset.id;
        const reservation = this.data.reservations.find(r => r.id == id);
        
        if (!reservation.can_cancel) {
            wx.showToast({
                title: '当前预约无法取消',
                icon: 'none'
            });
            return;
        }

        wx.showModal({
            title: '取消预约',
            content: '确定要取消这个预约吗？取消后无法恢复。',
            confirmText: '确定取消',
            confirmColor: '#ff4444',
            success: async (res) => {
                if (res.confirm) {
                    try {
                        const result = await reservationAPI.cancelReservation(id, '用户主动取消');
                        
                        if (result.success) {
                            wx.showToast({
                                title: '预约已取消',
                                icon: 'success'
                            });
                            // 刷新列表
                            this.loadReservations();
                        }
                    } catch (error) {
                        wx.showToast({
                            title: error.message || '取消失败',
                            icon: 'none'
                        });
                    }
                }
            }
        });
    },

    // 显示二维码
    showQRCode(e) {
        const qrPath = e.currentTarget.dataset.qr;
        const code = e.currentTarget.dataset.code;
        
        if (!qrPath) {
            wx.showToast({
                title: '二维码不存在',
                icon: 'none'
            });
            return;
        }

        // 预览二维码图片
        wx.previewImage({
            urls: [qrPath],
            current: qrPath
        });
    },

    // 加载统计信息
    async loadStats() {
        try {
            const result = await reservationAPI.getReservationStats();
            
            if (result.success) {
                // 可以在页面显示统计信息
                console.log('用户预约统计:', result.data);
            }
        } catch (error) {
            console.error('加载统计失败:', error);
        }
    },

    // 下拉刷新
    async onPullDownRefresh() {
        await this.loadReservations();
        wx.stopPullDownRefresh();
    },

    // 上拉加载更多
    onReachBottom() {
        this.loadMore();
    }
};

// 预约详情页面示例
const ReservationDetailPage = {
    data: {
        reservation: null,
        loading: true
    },

    onLoad(options) {
        const id = options.id;
        if (id) {
            this.loadDetail(id);
        }
    },

    async loadDetail(id) {
        try {
            const result = await reservationAPI.getReservationDetail(id);
            
            if (result.success) {
                this.setData({
                    reservation: result.data,
                    loading: false
                });
            }
        } catch (error) {
            wx.showToast({
                title: error.message || '加载详情失败',
                icon: 'none'
            });
            this.setData({ loading: false });
        }
    },

    // 取消预约
    async cancelReservation() {
        const reservation = this.data.reservation;
        
        if (!reservation.can_cancel) {
            wx.showToast({
                title: '当前预约无法取消',
                icon: 'none'
            });
            return;
        }

        wx.showModal({
            title: '取消预约',
            content: '确定要取消这个预约吗？',
            success: async (res) => {
                if (res.confirm) {
                    try {
                        const result = await reservationAPI.cancelReservation(reservation.id);
                        
                        if (result.success) {
                            wx.showToast({
                                title: '预约已取消',
                                icon: 'success'
                            });
                            // 返回上一页并刷新
                            setTimeout(() => {
                                wx.navigateBack();
                            }, 1500);
                        }
                    } catch (error) {
                        wx.showToast({
                            title: error.message || '取消失败',
                            icon: 'none'
                        });
                    }
                }
            }
        });
    },

    // 保存二维码
    saveQRCode() {
        const qrPath = this.data.reservation.qr_code_path;
        if (!qrPath) return;

        wx.saveImageToPhotosAlbum({
            filePath: qrPath,
            success: () => {
                wx.showToast({
                    title: '二维码已保存',
                    icon: 'success'
                });
            },
            fail: () => {
                wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                });
            }
        });
    }
};